/* eslint-disable */
<template>
	<div>
		<el-dialog class="assignDataGroup newlyForm" :title="$t('components.assignDatagroup.title')" :visible.sync="assignDataGroupVisible" width="80%" :close-on-click-modal="false"  @close="closeAssighDialog">
			<el-form :rules="rules2"  :inline="false" :model="dataSourceRow" ref="dataSourceRow" label-width="110px" >
				<el-row>
					<el-col :span="6">
						<el-form-item :label="$t('common.byUserName')+'：'" >
							<el-input  v-model="dataSourceRow.byUserName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.empName')+'：'" >
							<el-input  v-model="dataSourceRow.empName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.positionName')+'：'"  >
							<el-input  v-model="dataSourceRow.positionName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.orgName')+'：'">
							<el-input  v-model="dataSourceRow.orgName" disabled :placeholder="$t('common.defaultBySys')"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6" v-if="isSwitchRole==1">
	                    <el-form-item :label="$t('common.subsysName')+'：'" prop="subSysCode">
							<el-select @change="changesubSys" v-model="dataSourceRow.subSysCode" :placeholder="$t('common.selectPlaceholder')" clearable>
								<el-option v-for="(item,index) in subSystemNameOptions" :key="index" :label="item.label" :value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6" v-if="isSwitchRole==1">
	                    <el-form-item :label="$t('common.roleName')+'：'"  prop="roleName">
	                    	<el-select  v-model="dataSourceRow.roleName" filterable :placeholder="$t('common.selectPlaceholder')" clearable :filter-method="getroleList">
								<el-option  @click.native="dataSourceRow.resourceName='';dataSourceRow.roleId=item.roleId;resourceOptionsFun('')"  v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.roleName"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6" >
						<el-form-item :label="$t('common.resourceName')+'：'" prop="resourceName" >
		  					 <el-select v-model="dataSourceRow.resourceName" filterable :placeholder="$t('common.selectPlaceholder')"   :filter-method="resourceOptionsFun">
							    <el-option @click.native="handleSelectResource(item)"
							      v-for="item in resourceOptions"
							      :key="item.code"
							      :label="item.label"
							      :value="item.id">
							    </el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item :label="$t('common.dataGroupName')+'：'" >
							<el-input  v-model="dataSourceRow.dataGroupName"  :placeholder="$t('common.inputPlaceholder')" ></el-input>
						</el-form-item>
				    </el-col>
					<el-col :span="6" style="padding-left:25px;padding-bottom: 20px;">
						<el-button  type="primary" @click="searchDataGroup" >{{$t('common.searchBtn')}}</el-button>
						<el-button   @click="resetDataGroup" >{{$t('common.resetBtn')}}</el-button>
					</el-col>
				</el-row>
			</el-form>
			<el-row class="dataGroupAssignList">
				<!--可选资源列表-->
			  <el-col :span="10">
			  		<div class="marginB10 font-bold">{{$t('components.assignDatagroup.resourceList')}}</div>
			  		<el-table   ref="resourceList" :data="resourceList" border max-height="500"  style="width: 100%" @selection-change="selectAddListChange" >
			  		 	<el-table-column  type="selection" width="55"></el-table-column>
			  		 	<el-table-column  prop="ruleType" :label="$t('common.ruleType')" show-overflow-tooltip></el-table-column>
					    <el-table-column  prop="dataGroupName" :label="$t('common.dataGroupName')"  show-overflow-tooltip> </el-table-column>
					    <el-table-column  prop="isCustom" :label="$t('components.assignDatagroup.isCustom')"  show-overflow-tooltip>
					    	<template slot-scope="scope">{{ scope.row.isCustom==1?$t('common.is'):$t('common.not') }}</template>
					    </el-table-column>
					</el-table>
					<el-pagination
					      @size-change="pageSizeChange1"
					      @current-change="handleCurrentChangePage1"
					      :current-page="pagination1.pageNum"
					      :page-sizes="[10,20, 50, 100, 200]"
					      :page-size="pagination1.pageSize"
					      :pager-count="5"
					      layout="->,prev, pager, next,  sizes,total"
					      :total="pagination1.totalSize">
					</el-pagination>
			  </el-col>
			  <!--操作按钮-->
			  <el-col :span="4" class="alignC">
			  	<div>
			  		<el-button  type="primary"  @click="addToRight" :disabled="!addSelectMultipleSelection.length">{{$t('common.add')}}<i class="el-icon-arrow-right"></i></el-button>
			  	</div>
			  	<div>
			  		<el-button type="danger"  @click="delfromRight" :disabled="!delSelectMultipleSelection.length"> <i class="el-icon-arrow-left"></i>{{$t('common.remove')}} </el-button>
			  	</div>
			  	<div>
			  		<el-button class="removeBtn"  v-if="dataSourceRow.customDatagroup!==0 && dataSourceRow.ownerSysId==dataSourceRow.systemId" @click="autoDefinedDataGroup">{{$t('common.autoDefined')}}</el-button>
			  	</div>

			  </el-col>
			  <!--已添加资源列表-->
			  <el-col :span="10">
			  		<div class="marginB10 font-bold">{{$t('components.assignDatagroup.selectResorceList')}}</div>
			  		<el-table ref="selectResorceList"  :data="selectResorceList" max-height="500"    border  style="width: 100%"  @selection-change="selectDelListChange">
			  		 	<el-table-column  type="selection" width="55"></el-table-column>
			  		 	<el-table-column  prop="ruleType" :label="$t('common.ruleType')" show-overflow-tooltip></el-table-column>
					    <el-table-column prop="dataGroupName" :label="$t('common.dataGroupName')"   show-overflow-tooltip></el-table-column>
					    <el-table-column  prop="isCustom" :label="$t('components.assignDatagroup.isCustom')"  show-overflow-tooltip>
					    	<template slot-scope="scope">{{ scope.row.isCustom==1?$t('common.is'):$t('common.not') }}</template>
					    </el-table-column>
					    <el-table-column prop="startTm" :label="$t('common.startTm')" :formatter="formatter"  show-overflow-tooltip></el-table-column>
					    <el-table-column prop="endTm" :label="$t('common.endTm')"  :formatter="formatter"  show-overflow-tooltip></el-table-column>
					  </el-table>
					  <el-pagination
					      @size-change="pageSizeChange2"
					      @current-change="handleCurrentChangePage2"
					      :current-page="pagination2.pageNum"
					      :page-sizes="[10,20, 50, 100, 200]"
					      :page-size="pagination2.pageSize"
					      :pager-count="5"
					      layout="->,prev, pager, next,sizes,total"
					      :total="pagination2.totalSize">
					</el-pagination>
			  </el-col>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button  @click="closeAssighDialog">{{$t('common.close')}}</el-button>
			</div>
		</el-dialog>
		<!-- 添加角色授权的弹窗 -->
		<!--在从可选列表勾选到已选列表的时候进行配置生效失效时间-->
		<validity-date path='noStart'  :earliestTime="new Date().getTime()"   :visible="dataValidityVisible" @validityDateClose="dataGroupValidityClose"  @submitDateForm="submitDataGroupValidity"></validity-date>
		<!--resourceNameList，systemList都是根据用户选择带出来的下拉选项，所以在子组件中要注意实时更新-->
		<custom-datagroup :visible="showCustomDatagroup" @customDialogClose="customDialogClose" @customDialogSave="customDialogSave"  :formInfo="dataSourceRow"  ></custom-datagroup>

	</div>

</template>

<script>
import validityDate from "./validityDate"
import customDatagroup from "./customDatagroup"
import {
    Message, Notification, MessageBox, Loading
} from 'element-ui'
export default {
    name: 'assignDatagroup',
    props: [
        'visible', 'form'
    ],
    components: {
	    validityDate, customDatagroup
    },
    data () {
        return {
            assignDataGroupVisible: false,
            dataValidityVisible: false,
            selectResorceList: [], // 已选数据组
            submitSelect: [], // 从左侧勾选的与右侧不重复的资源
            addSelectMultipleSelection: [],
            delSelectMultipleSelection: [],
		        resourceList: [], // 可选数据组
		        pagination1: {
                totalSize: 0,
                pageSize: 10,
                pageNum: 1,
                totalPage: 0
            },
            pagination2: {
                totalSize: 0,
                pageSize: 10,
                pageNum: 1,
                totalPage: 0
            },
            dataSourceRow: {},
            rules2: {
                resourceName: [
                    { required: true, message: this.$t('validateWornText.selectResourceName'), trigger: 'change' }
                ],
                roleName: [
                    { required: true, message: this.$t('validateWornText.selectRoleName'), trigger: 'change' }
                ],
                subSysCode: [
                    { required: true, message: this.$t('validateWornText.selectSubSysCode'), trigger: 'change' }
                ]
            },
            showCustomDatagroup: false,
            roleList: [],
            subSystemNameOptions: [],
            resourceOptions: [],
            systemInfo: {},
            isSwitchRole: ''
        }
    },
    watch: {
        visible: 'visibleChange'
    },
    mounted () {
        this.searchSystemInfo()
    },
    methods: {
    	async searchSystemInfo(){
    		this.systemInfo = await this.$getSystemInfo()
    		this.isSwitchRole = this.systemInfo.isSwitchRole
    	},
        visibleChange (val) {
            this.assignDataGroupVisible = val
            if (val) {
                this.resourceOptionsFun('')
                this.dataSourceRow = this.$deepCopy(this.form)
                // 向后台发起请求请求子系统名称;
                this.getSubSystemList()
                this.searchBybyUserName()// 查询用户信息
            }
        },
        /**
          * @author：xmj
          * @function:获取子系统列表
          */
        async getSubSystemList (val) {
            this.subSystemNameOptions = await this.$getSubSystemList(val)
        },
        submitDataGroupValidity (dialogForm) { // 右移,将数据关联到子账号，并设置生效失效时间
            let urlH = '/dev-basp-user/accountDataGroup/save'
            let param = []
            for (let i = 0; i < this.submitSelect.length; i++) {
                param.push({
                    resourceId: this.submitSelect[i].resourceId,
                    dataGroupId: this.submitSelect[i].dataGroupId,
                    byAccountId: this.dataSourceRow.byAccountId,
                    startTm: dialogForm.startTm,
                    endTm: dialogForm.endTm
                })
            }
            this.$httpExt().post(urlH, param)
            .then((response) => {
                this.searchDataGroup()
                this.addSelectMultipleSelection = []
                this.dataValidityVisible = false
                this.showCustomDatagroup = false
            }, (response) => {
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        dataGroupValidityClose () {
            this.dataValidityVisible = false
        },
        resetDataGroup () { // 授权数据组表单查询重置
            this.$refs['dataSourceRow'].resetFields()
            this.dataSourceRow.roleName = ''
            this.dataSourceRow.dataGroupName = ''
        },
        async resourceOptionsFun (queryString) { // 资源名称模糊搜索
            this.resourceOptions = await this.$resourceOptionsFun(queryString, this.dataSourceRow.roleId)
        },
        handleSelectResource (item) { // 选择资源后
            this.dataSourceRow.resourceCode = item.code
            this.dataSourceRow.resourceId = item.id
            this.dataSourceRow.customDatagroup = item.customDatagroup
            this.dataSourceRow.systemId = item.systemId
            this.dataSourceRow.ownerSysId = item.ownerSysId
            this.dataSourceRow.paramStruct = item.paramStruct
	        this.dataSourceRow.paramUrl=item.paramUrl
	        this.dataSourceRow.paramType=item.paramType
            this.dataSourceRow.dataGroupName = ''
            this.pagination2.pageNum = 1
            this.pagination1.pageNum = 1
            this.selectResorceList = []
            this.resourceList = []
        },
        changesubSys (val) {
            this.dataSourceRow.roleName = ''
            this.getroleList('')
        },
        async getroleList (val) { // 根据子系统编码查角色
            if (!this.dataSourceRow.byAccountId) {
                return
            }
            this.roleList = await this.$getroleListFun(val, this.dataSourceRow.subSysCode, this.dataSourceRow.byAccountId)
        },
        roleChange () {
            this.searchDataGroup() // 重新搜索列表
        },
        searchDataGroup () { // 搜索数据组
            this.$refs['dataSourceRow'].validate((valid) => {
                if (valid) {
                    this.pagination2.pageNum = 1
                this.pagination1.pageNum = 1
                    this.searchDataGroupList(0)// 可选列表
                    this.searchDataGroupList(1) // 已选列表
                } else {
                    return false
                }
            })
        },
        closeAssighDialog () { // 授权数据组表单关闭
            this.$refs['dataSourceRow'].resetFields()// 重置表单
            this.selectResorceList = []
            this.resourceList = []
            this.dataSourceRow = {
                subSystemName: "",
                byUserName: "",
                sysUserName: "",
                empName: "",
                positionName: "",
                orgName: "",
                byAccountId: "",
                sysAccountStatus: "",
                username: '',
                roleName: '',
                resourceName: '',
                dataGroupName: '',
                subSysCode: ''
            }
            this.pagination1.totalSize = 0
            this.pagination1.pageNum = 1
            this.pagination2.totalSize = 0
            this.pagination2.pageNum = 1
            this.$emit('closeAssighDialog')
        },
        // 根据百源账号名查询相关信息;
        searchBybyUserName () {
            // 为了避免在清空select选项的时候会触发on-change事件;
            if (this.dataSourceRow.byUserName.length > 0) {
                this.$httpExt().get('/dev-basp-user/userRole/queryUserInfo/' + this.dataSourceRow.byUserName)
                .then((response) => {
                    if (response.succ == "ok") {
                        this.dataSourceRow.sysUserName = response.result[0] ? response.result[0].sysUserName : ""
                        this.dataSourceRow.empName = response.result[0] ? response.result[0].empName : ""
                        this.dataSourceRow.positionName = response.result[0] ? response.result[0].positionName : ""
                        this.dataSourceRow.orgName = response.result[0] ? response.result[0].orgName : ""
                        this.dataSourceRow.byAccountId = response.result[0] ? response.result[0].byAccountId : ""
                        this.dataSourceRow.sysAccountStatus = response.result[0] ? response.result[0].sysAccountStatus : ""
                    }
                }, (response) => {
                    Notification.error({
                        title: this.$t('common.exception'),
                        message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                    })
				  })
            }
        },
        searchDataGroupList (type) { // 查询数据组列表
            var urlH = (type == 0) ? '/dev-basp-user/accountDataGroup/selectOptionalDataGroup' : '/dev-basp-user/accountDataGroup/selectedDataGroup'
            var param = {
                /* sysUserName :this.dataSourceRow.sysUserName, */
            resourceId: this.dataSourceRow.resourceId,
            byAccountId: this.dataSourceRow.byAccountId,
            roleId: this.dataSourceRow.roleId,
            dataGroupName: this.dataSourceRow.dataGroupName,
            pageNum: type == 0 ? this.pagination1.pageNum : this.pagination2.pageNum,
            pageSize: type == 0 ? this.pagination1.pageSize : this.pagination2.pageSize
            }
            this.$httpExt().post(urlH, param)
            .then((response) => {
                var body = response.result
                if (type == 0) { // 可选
                    this.resourceList = body.data
                    this.pagination1.totalSize = body.totalSize
                } else { // 已选
                    this.selectResorceList = body.data
                    this.pagination2.totalSize = body.totalSize
                }
            }, (response) => {
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        handleCurrentChangePage1 (val) { // 可选列表分页
            this.pagination1.pageNum = val
            this.searchDataGroupList(0)// 可选列表
        },
        pageSizeChange1 (val) { // 可选列表分页
            this.pagination1.pageNum = 1
            this.pagination1.pageSize = val
            this.searchDataGroupList(0)// 可选列表
        },
        handleCurrentChangePage2 (val) { // 已选列表分页
            this.pagination2.pageNum = val
            this.searchDataGroupList(1)// 已选列表
        },
        pageSizeChange2 (val) { // 已选列表分页
            this.pagination2.pageNum = 1
            this.pagination2.pageSize = val
            this.searchDataGroupList(1)// 已选列表
        },
		     /* 分配数据组相关操作 */
		    // 左侧列表勾选
		    selectAddListChange (val) {
            this.addSelectMultipleSelection = val
        },
        // 右侧列表勾选
        selectDelListChange (val) {
            this.delSelectMultipleSelection = val
        },
        addToRight () { // 加入右边列表
            var submitSelect = this.$deepCopy(this.addSelectMultipleSelection, []) // 提交到后台的需要移到右边的数据
            if (submitSelect.length) {
                this.submitSelect = submitSelect
                this.dataValidityVisible = true
            } else {
                this.$message({
                    message: window.sessionStorage.getItem('lang') == 'zh-CN' ? '您勾选的数据组已关联该账号' : 'The data group you checked has been associated with the account',
                    type: 'warning'
                })
            }
        },
        delfromRight () { // 删除右边列表数据
            if (this.delSelectMultipleSelection.length) {
                this.$confirm(this.$t('components.assignDatagroup.removeTip'), this.$t('common.tip'), {
                    confirmButtonText: this.$t('common.submitOption'),
                    cancelButtonText: this.$t('common.cancelOption')
                }).then(() => {
                    var submitSelect = this.$deepCopy(this.delSelectMultipleSelection, []) // 提交到后台的需要移到左边的数据
                var urlH = '/dev-basp-user/accountDataGroup/state'
                var param = []
                for (var i = 0; i < submitSelect.length; i++) {
                    param.push({
                        resourceId: submitSelect[i].resourceId,
                        byAccountId: this.dataSourceRow.byAccountId,
                        dataGroupId: submitSelect[i].dataGroupId,
                        id: submitSelect[i].id,
                        status: 0
                    })
                }
                this.$httpExt().post(urlH, param)
                    .then((response) => {
                        this.searchDataGroup()
                        this.delSelectMultipleSelection = []
                    }, (response) => {
                        Notification.error({
                            title: this.$t('common.exception'),
                            message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                        })
                    })
                }).catch(() => {
                })
            }
        },
        autoDefinedDataGroup () {
            this.$refs['dataSourceRow'].validate((valid) => {
		    		if (valid) {
		    			var urlH = '/dev-basp-user/accountDataGroup/selectCustomDateGroup'
		    			var param = {
		    				resourceId: this.dataSourceRow.resourceId,
		    				resourceName: this.dataSourceRow.resourceName,
		    				username: this.dataSourceRow.byUserName,
		    				byAccountId: this.dataSourceRow.byAccountId
		    			}
                    this.$httpExt().post(urlH, param)
                        .then((response) => {
                            this.dataSourceRow.dataGroupId = response.result.dataGroupId
                            this.dataSourceRow.dataGroupName = response.result.dataGroupName
                            this.showCustomDatagroup = true
                        }, (response) => {
                            Notification.error({
                                title: this.$t('common.exception'),
                                message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                            })
                        })
				    } else {
				    	return false
                }
            })
        },
        // 自定义数据组相关操作
        customDialogClose () { // 关闭自定义数据组弹框
            this.showCustomDatagroup = false
        },
        customDialogSave (dataSourceRow, currentCheckedNodes) { // 创建了自定义数据组后保存
            this.saveResourceChecked(dataSourceRow, currentCheckedNodes)
        },
        saveResourceChecked (dataSourceRow, currentCheckedNodes) { // 提交该自定义数据组的勾选
            let codeList = []
            for (let i = 0; i < currentCheckedNodes.length; i++) {
                codeList.push(currentCheckedNodes[i].code)
            }
            let param = {
                dataGroupId: this.dataSourceRow.dataGroupId,
                resourceId: this.dataSourceRow.resourceId,
		        codeList:codeList,
		        paramUrl:this.dataSourceRow.paramUrl
            }
            let urlH = "/dev-basp-user/accountDataGroup/saveCustomParams"
            let loadingInstance = Loading.service({ fullscreen: true })
            this.$httpExt().post(urlH, param)
            .then((response) => {
                loadingInstance.close()
                this.$message({
                        message: response.msg ? response.msg : this.$t('assignDatagroup.appendSuccess'),
                        type: 'success'
                })
                this.appendDataGroupToAccount(dataSourceRow)
            }, (response) => {
                loadingInstance.close()
                Notification.error({
                    title: this.$t('common.exception'),
                    message: response.msg ? response.msg : this.$t('common.exceptionWornText')
                })
            })
        },
        appendDataGroupToAccount (dataSourceRow) { // 将新建立的数据组绑定到子账号
            this.submitSelect = [{
                resourceId: dataSourceRow.resourceId,
                dataGroupId: dataSourceRow.dataGroupId
            }]
            // this.submitDataGroupValidity(dataSourceRow)  //右移
            this.searchDataGroup()
            this.addSelectMultipleSelection = []
            this.showCustomDatagroup = false
        },
        formatter (row, column) { // 状态信息中表格展开项的code转为name
            switch (column.property) {
            case "startTm":return this.$format(row.startTm, "yyyy/MM/dd hh:mm:ss")  // 开始时间
            case "endTm":return this.$format(row.endTm, "yyyy/MM/dd hh:mm:ss")  // 开始时间
            default : return row[column.property]
            }
        }
    }
}
</script>
<style lang="less">
.assignDataGroup{
	.el-dialog{
		min-width:1050px;
	}
	.dataGroupAssignList{
		padding: 0 30px;
	}
	.el-autocomplete{
		width:100%;
	}
	.el-button.removeBtn{
		background: #FFFFFF;
		border: 1px solid #409EFF;
		border-radius: 4px;
		color:#409EFF ;
	}
	.alignC{
		padding-top: 50px;
		text-align: center;
		line-height: 55px;
		.el-button--danger{
			margin-left: 0;
		}
	}
	.descText.textspical{
	    padding-bottom: 0px;
	}
	.marginB10{
		margin-bottom: 10px;
	}
}
</style>
